#########################################################################################################
# 从 十万员工数据.xlsx 文件中随机抽取 10名幸运员工 将获奖通知文档，以 “工号-姓名-获奖通知.docx” 的命名方式进行WORD存储  #
#########################################################################################################
import random

import xlwings as xw
from docx import Document
# 获取中奖名单
from docx.shared import Inches


def get_winner_list(staff_num, max_num):
    winner_list = []
    for i in range(staff_num):
        winner_list.append(random.randint(2, max_num))
    return winner_list


# 获取中奖者信息
def get_winner_info(in_filepath):
    winner_info = []
    xw_app = xw.App(visible=False, add_book=False)
    wb = xw_app.books.open(in_filepath, read_only=True)
    sht = wb.sheets[0]
    info = sht.used_range
    # 取最大行数
    nrows = info.last_cell.row
    # print(nrows)
    # 取最大列数
    ncolumns = info.last_cell.column
    # print(ncolumns)
    winner_list = get_winner_list(10, nrows)
    # print(winner_list)
    for i in winner_list:
        winner_info.append(xw.Range('A' + str(i) + ':' + str(chr(ord('A') + ncolumns - 1)) + str(i)).value)
    wb.close()
    xw_app.quit()
    xw_app.kill()
    return winner_info


# 生成word获奖通知
def generate_word(out_filepath, winner_info):
    for i in range(len(winner_info)):
        # print(winner_info[i])
        docx = Document()
        docx.add_heading("获奖通知", level=1)

        docx.add_paragraph("恭喜 {} 部门的 {} ，您获奖了！".format(winner_info[i][2], winner_info[i][1]), "Title")
        docx.add_picture("pic.jpg", width=Inches(6))
        para = docx.add_paragraph("你的运气可")
        para.add_run("真不错！！！")
        docx.save(out_filepath + "/%s-获奖通知.docx" % winner_info[i][1])


if __name__ == '__main__':
    in_filepath = './result/十万员工数据.xlsx'
    out_filepath = './result'

    winner_info = get_winner_info(in_filepath)
    print(winner_info)

    generate_word(out_filepath, winner_info)
    print('生成完毕')
